package com.qianfeng.android.baoman;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.adapter.CommonFindRecourseAdapter;
import com.qianfeng.android.baoman.adapter.SubjectFindRecourseAdapter;
import com.qianfeng.android.baoman.model.RecourseList;
import com.qianfeng.android.baoman.model.Subject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

//发现-资源
public class RecourseFindActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {


    private SubjectFindRecourseAdapter subjectFindRecourseAdapter;

    //网络加载失败提示信息
    private LinearLayout load_layout;

    private LinkedList<Subject> specialRecommendRecourse;
    private String hotUrl;
    private String addUrl;
    private String updateUrl;
    private String classicsEndUrl;
    private String shortFourUrl;
    private String wonderfulChoiceUrl;
    private String weekUrl;
    private String monthUrl;
    private String yearUrl;
    private List<RecourseList> lastAddRecourse;
    private List<RecourseList> lastUpdateRecourse;
    private List<RecourseList> hotSerializeRecourse;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_recourse_find);


        ImageView backIcon = (ImageView) findViewById(R.id.find_recourse_top_back);
        backIcon.setOnClickListener(this);

        load_layout = (LinearLayout) findViewById(R.id.load_layout);


        //专题推荐
        specialRecommendRecourse = new LinkedList<Subject>();

        GridView specialRecommendGridView = (GridView) findViewById(R.id.find_recourse_special_recommend);
        if (specialRecommendGridView != null) {
            subjectFindRecourseAdapter = new SubjectFindRecourseAdapter(this, specialRecommendRecourse);
            specialRecommendGridView.setAdapter(subjectFindRecourseAdapter);

            getHttpSubjectData();

        }


        //热门连载
        hotSerializeRecourse = new LinkedList<RecourseList>();

        GridView hotSerializeGridView = (GridView) findViewById(R.id.find_recourse_hot_serialize);
        if (hotSerializeGridView != null) {

            hotUrl = "http://hahaapi.ibaozou.com/api/v1/hot/1.json";
            CommonFindRecourseAdapter hotSerializeAdapter = new CommonFindRecourseAdapter(this, hotSerializeRecourse);
            hotSerializeGridView.setAdapter(hotSerializeAdapter);
            hotSerializeGridView.setOnItemClickListener(this);
            getHttpUtils(hotSerializeGridView, hotUrl, hotSerializeRecourse, hotSerializeAdapter);


        }

        //最新上架
        lastAddRecourse = new LinkedList<RecourseList>();

        GridView lastAddGridView = (GridView) findViewById(R.id.find_recourse_last_add);
        if (lastAddGridView != null) {

            addUrl = "http://hahaapi.ibaozou.com/api/v1/hot/3.json";
            CommonFindRecourseAdapter lastAddAdapter = new CommonFindRecourseAdapter(this, lastAddRecourse);
            lastAddGridView.setAdapter(lastAddAdapter);
            lastAddGridView.setOnItemClickListener(this);

            getHttpUtils(lastAddGridView, addUrl, lastAddRecourse, lastAddAdapter);
        }

        //最近更新
        lastUpdateRecourse = new LinkedList<RecourseList>();

        GridView lastUpdateGridView = (GridView) findViewById(R.id.find_recourse_last_update);

        if (lastUpdateGridView != null) {

            updateUrl = "http://hahaapi.ibaozou.com/api/v1/fresh_list.json?type=2";
            CommonFindRecourseAdapter lastUpdateAdapter = new CommonFindRecourseAdapter(this, lastUpdateRecourse);
            lastUpdateGridView.setAdapter(lastUpdateAdapter);
            lastUpdateGridView.setOnItemClickListener(this);

            getHttpUtils(lastUpdateGridView, updateUrl, lastUpdateRecourse, lastUpdateAdapter);
        }


        if (specialRecommendRecourse.size() == 0 && lastAddRecourse.size() == 0 &&
                lastUpdateRecourse.size() == 0 && hotSerializeRecourse.size() == 0) {
            load_layout.setVisibility(View.VISIBLE);

        }


        //点击 全部专题 或 > 的监听事件
        TextView subjectMoreTxt = (TextView) findViewById(R.id.find_recourse_special_recommend_more_txt);
        subjectMoreTxt.setOnClickListener(this);
        TextView subjectMore = (TextView) findViewById(R.id.find_recourse_special_recommend_more);
        subjectMore.setOnClickListener(this);


        //热门连载 全部 、 >
        TextView hotSerializeMoreTxt = (TextView) findViewById(R.id.find_recourse_hot_serialize_more_txt);
        hotSerializeMoreTxt.setOnClickListener(this);
        TextView hotSerializeMore = (TextView) findViewById(R.id.find_recourse_hot_serialize_more);
        hotSerializeMore.setOnClickListener(this);

        //最近上架 全部 、 >
        TextView lastAddMoreTxt = (TextView) findViewById(R.id.find_recourse_last_add_more_txt);
        lastAddMoreTxt.setOnClickListener(this);
        TextView lastAddMore = (TextView) findViewById(R.id.find_recourse_last_add_more);
        lastAddMore.setOnClickListener(this);

        //最近更新 全部 、 >
        TextView lastUpdateMoreTxt = (TextView) findViewById(R.id.find_recourse_last_update_more_txt);
        lastUpdateMoreTxt.setOnClickListener(this);
        TextView lastUpdateMore = (TextView) findViewById(R.id.find_recourse_last_update_more);
        lastUpdateMore.setOnClickListener(this);


        //经典完结
        TextView classicsEndTxt = (TextView) findViewById(R.id.find_recourse_classics_end_txt);
        if (classicsEndTxt != null) {
            classicsEndUrl = "http://hahaapi.ibaozou.com/api/v1/hot/2.json";
            classicsEndTxt.setOnClickListener(this);
        }

        //短片四格
        TextView shortFourTxt = (TextView) findViewById(R.id.find_recourse_short_four_txt);
        if (shortFourTxt != null) {
            shortFourUrl = "http://hahaapi.ibaozou.com/api/v1/hot/6.json";
            shortFourTxt.setOnClickListener(this);
        }

        //全彩精选
        TextView wonderfulChoiceTxt = (TextView) findViewById(R.id.find_recourse_wonderful_choice_txt);
        if (wonderfulChoiceTxt != null) {
            wonderfulChoiceUrl = "http://hahaapi.ibaozou.com/api/v1/hot/4.json";
            wonderfulChoiceTxt.setOnClickListener(this);
        }

        //周排行
        TextView weekTxt = (TextView) findViewById(R.id.find_recourse_week_ranked_txt);
        if (weekTxt != null) {
            weekUrl = "http://hahaapi.ibaozou.com/api/v1/rank.json?type=week";
            weekTxt.setOnClickListener(this);
        }

        //月排行
        TextView monthTxt = (TextView) findViewById(R.id.find_recourse_month_ranked_txt);
        if (monthTxt != null) {
            monthUrl = "http://hahaapi.ibaozou.com/api/v1/rank.json?type=month";
            monthTxt.setOnClickListener(this);
        }

        //年排行
        TextView yearTxt = (TextView) findViewById(R.id.find_recourse_year_ranked_txt);
        if (yearTxt != null) {
            yearUrl = "http://hahaapi.ibaozou.com/api/v1/rank.json?type=year";
            yearTxt.setOnClickListener(this);
        }


        //按分类检索
        Button searchCategoryBtn = (Button) findViewById(R.id.find_recourse_search_by_category_btn);
        searchCategoryBtn.setOnClickListener(this);

    }


    //获取专题推荐的网络数据
    public void getHttpSubjectData() {
        HttpUtils httpUtils = new HttpUtils();

        httpUtils.send(HttpRequest.HttpMethod.GET,
                "http://hahaapi.ibaozou.com/api/v1/subjects.json",
                new RequestCallBack<String>() {

                    @Override
                    public void onSuccess(ResponseInfo<String> jsonObjectResponseInfo) {
                        String result = jsonObjectResponseInfo.result;
                        List<Subject> subjectList = new LinkedList<Subject>();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            JSONArray subjectsArray = jsonObject.getJSONArray("subjects");

                            for (int i = 0; i < 4; i++) {
                                JSONObject subjectsArrayJSONObject = subjectsArray.getJSONObject(i);

                                Log.d("RecourseFindActivity", "--->" + subjectsArrayJSONObject);
                                Subject subject = new Subject();
                                subject.parseJSON(subjectsArrayJSONObject);

                                subjectList.add(subject);
                            }
                            specialRecommendRecourse.addAll(subjectList);
                            subjectFindRecourseAdapter.notifyDataSetChanged();

                            load_layout.setVisibility(View.GONE);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(RecourseFindActivity.this, "连接失败,网络问题", Toast.LENGTH_SHORT).show();

                        load_layout.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 得到实际加载个数
     *
     * @param gridView
     * @param size
     * @return
     */

    private int getRealCount(GridView gridView, int size) {
        int realCount = 0;

        int numColumns = 0;   //GridView每行显示的个数


        numColumns = gridView.getNumColumns();
        if (numColumns == -1) {   //为-1 的时候是自动补全的
            numColumns = 4;
        }

        int row = size / numColumns;

        if (row > 0) {
            realCount = row * numColumns;
        }
        return realCount;

    }

    /**
     * 使用xUtils解析数据
     *
     * @param url  给定的url
     * @param data 数据
     */
    private void getHttpUtils(final GridView gridView,
                              String url,
                              final List<RecourseList> data,
                              final CommonFindRecourseAdapter adapter) {

        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(
                HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {



                    @Override
                    public void onSuccess(ResponseInfo<String> jsonObjectResponseInfo) {
                        String result = jsonObjectResponseInfo.result;

                        LinkedList<RecourseList> recourse = new LinkedList<RecourseList>();

                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            JSONArray listsArray = jsonObject.getJSONArray("lists");

                            int realCount = getRealCount(gridView, listsArray.length());

                            for (int i = 0; i < realCount; i++) {


                                JSONObject recourseArrayJSONObject = listsArray.getJSONObject(i);

                                RecourseList recourseList = new RecourseList();

                                recourseList.parseJSON(recourseArrayJSONObject);



                                recourse.add(recourseList);
                            }

                            data.clear();
                            data.addAll(recourse);
                            adapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        load_layout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(RecourseFindActivity.this, "连接失败,网络问题", Toast.LENGTH_SHORT).show();
                        load_layout.setVisibility(View.GONE);
                    }
                }
        );
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        int id = view.getId();
        switch (id) {
            case R.id.find_recourse_top_back:   //返回键
                finish();
                break;

            case R.id.find_recourse_special_recommend_more_txt:  //全部专题
            case R.id.find_recourse_special_recommend_more:  // >

                intent = new Intent(RecourseFindActivity.this, AllSubjectActivity.class);
                break;

            //显示更多
            case R.id.find_recourse_hot_serialize_more_txt:
            case R.id.find_recourse_hot_serialize_more:
            case R.id.find_recourse_last_add_more_txt:
            case R.id.find_recourse_last_add_more:
            case R.id.find_recourse_last_update_more_txt:
            case R.id.find_recourse_last_update_more:
            case R.id.find_recourse_week_ranked_txt:
            case R.id.find_recourse_month_ranked_txt:
            case R.id.find_recourse_year_ranked_txt:
            case R.id.find_recourse_classics_end_txt:
            case R.id.find_recourse_short_four_txt:
            case R.id.find_recourse_wonderful_choice_txt:
                intent = new Intent(RecourseFindActivity.this, CommonRecourseFindActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("hotUrl", hotUrl);
                intent.putExtra("addUrl", addUrl);
                intent.putExtra("updateUrl", updateUrl);
                intent.putExtra("weekUrl", weekUrl);
                intent.putExtra("monthUrl", monthUrl);
                intent.putExtra("yearUrl", yearUrl);
                intent.putExtra("classicsEndUrl", classicsEndUrl);
                intent.putExtra("shortFourUrl", shortFourUrl);
                intent.putExtra("wonderfulChoiceUrl", wonderfulChoiceUrl);
                break;

            case R.id.find_recourse_search_by_category_btn:    //按分类检索
                intent = new Intent(RecourseFindActivity.this,SearchCategoryFindActivity.class);
                break;
        }

        if (intent != null) {
            startActivity(intent);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int viewId = parent.getId();
        Intent intent = null;

        switch (viewId) {
            case R.id.find_recourse_hot_serialize:
                intent = new Intent(this, CartoonItemDetailsActivity.class);
                RecourseList hotRecourse = hotSerializeRecourse.get(position);
                intent.putExtra("hotRecourse",hotRecourse);
                break;
            case R.id.find_recourse_last_add:
                intent = new Intent(this, CartoonItemDetailsActivity.class);
                RecourseList addRecourse = lastAddRecourse.get(position);
                intent.putExtra("addRecourse",addRecourse);
                break;
            case R.id.find_recourse_last_update:
                intent = new Intent(this, CartoonItemDetailsActivity.class);
                RecourseList updateRecourse = lastUpdateRecourse.get(position);
                intent.putExtra("updateRecourse",updateRecourse);
                break;

        }
        if (intent != null) {
            startActivity(intent);
        }
    }
}
